/**
 * Created by TomSean on 2017/4/24.
 */
var IdentityEntityManager = function ($parent) {
    this.$parent = $parent;
    this.sysUtils = new kendoUtils();
    this.init();
    return this;
}
IdentityEntityManager.prototype = {
    init : function () {
        var _this = this;
        var fieldArray = this.sysUtils.getBindFieldArray(_this.$parent.find('.search-panel'));
        var functionArray = [
            {fName : 'find_data', fs : _this.findData},
            {fName : 'reset_btn', fs : _this.resetInfo}
            // {fName : 'delete_btn', fs : _this.deleteData}
        ];
        _this.models = new bindBaseModel(null, fieldArray, functionArray, null);
        _this.sysUtils.bindDoucment(_this.models, _this.$parent, _this);
        Utils.createDataDictDropDownList({div:this.$parent.find('#status'), parentModelKey:BASIS.DATA_STATUS.ROOT}, this);
        Utils.createDataDictDropDownList({div:this.$parent.find('#identityType'), parentModelKey:BASIS.IDENTITY_ENTITY_TYPE.ROOT}, this);
        _this.initTable();
        _this.findData();
    },
    /*
     * 重置按钮
     */
    resetInfo:function(e){
        var that = $(e.target).data("that");
        that.sysUtils.setBindFieldNull(that.models.bindFieldArray);
    },
    findData : function (e) {
        var _this = this;
        if (!isEmpty(e)) {
            _this = $(e.target).data('that');
        }
        var grid = _this.$parent.find('#identity_data_list').data('kendoGrid');
        var params = _this.sysUtils.getBindDocJson(_this.models.bindFieldArray);
        var dataT = {'jsonParam' : JSON.stringify(params)};
        var dataSource = _this.sysUtils.getDataSource({url : baseApiPath + 'identity/entity/list', data : dataT, dataType : 'odata'});
        grid.setDataSource(dataSource);
    },
    disableData : function (e) {
        var _this = this;
        if (!isEmpty(e)) {
            _this = $(e.target).data('that');
        }
        var ids = '';
        _this.$parent.find('input[type="checkbox"][name="identity_id"]:checked').each(function (inx, itm) {
            ids += $(itm).val() + ',';
        });
        if (isEmpty(ids)) {
            notification({title : '提示', message : '请勾选需要禁用的数据'}, 'info');
            return;
        }
        ids = ids.substring(0, ids.length - 1);
        var dataT = { 'ids' : ids };
        JsonpAjax(baseApiPath + 'identity/entity/disable', JSON.stringify(dataT), 'json', function (res) {
            _this.findData();
        }, true);
    },
    enableData : function (e) {
        var _this = this;
        if (!isEmpty(e)) {
            _this = $(e.target).data('that');
        }
        var ids = '';
        _this.$parent.find('input[type="checkbox"][name="identity_id"]:checked').each(function (inx, itm) {
            ids += $(itm).val() + ',';
        });
        if (isEmpty(ids)) {
            notification({title : '提示', message : '请勾选需要启用的数据'}, 'info');
            return;
        }
        ids = ids.substring(0, ids.length - 1);
        var dataT = { 'ids' : ids };
        JsonpAjax(baseApiPath + 'identity/entity/enable', JSON.stringify(dataT), 'json', function (res) {
            _this.findData();
        }, true);
    },
    deleteData : function (e) {
        var _this = this;
        if (!isEmpty(e)) {
            _this = $(e.target).data('that');
        }
        var ids = '';
        _this.$parent.find('input[type="checkbox"][name="identity_id"]:checked').each(function (inx, itm) {
            ids += $(itm).val() + ',';
        });
        if (isEmpty(ids)) {
            notification({title : '提示', message : '请勾选需要删除的数据'}, 'info');
            return;
        }
        notification({title : '警告', message : '删除操作无法回退，是否确认删除？'}, 'confirm', {
            callback : function () {
                ids = ids.substring(0, ids.length - 1);
                var dataT = { 'ids' : ids };
                JsonpAjax(baseApiPath + 'identity/entity/delete', JSON.stringify(dataT), 'json', function (res) {
                    _this.findData();
                }, true);
            }
        });
    },
    initTable : function () {
        var _this = this;
        var columns = [
            {
                width : 30,
                headerTemplate : '<input type="checkbox" gridId="identity_data_list" onclick="gridCheckAll(this)" />',
                template : '<input type="checkbox" name="identity_id" value="${id}" />'
            },
            {
                title : '实体内唯一标识',
                field : 'identityId'
            },
            {
                title : '可视识别码',
                field : 'identityVisualId'
            },
            {
                title : '实体类型',
                template : '#: Utils.getModelNameByParentKey(BASIS.IDENTITY_ENTITY_TYPE.ROOT, identityType)#'
            },
            {
                title : '状态',
                template : '#: Utils.getModelNameByParentKey(BASIS.DATA_STATUS.ROOT, status)#'
            },
            {
                title : '录入人',
                field : 'createUserId'
            },
            {
                title : '录入时间',
                field : 'createTime'
            }
        ];
        _this.sysUtils.createGird(_this.$parent.find('#identity_data_list'), {
            selectable : 'single',
            autoSync : true,
            columnMenu : true,
            pageable : {input : true, numeric : false},
            columns : columns,
            change : function(e) {
                var selected = $.map(this.select(), function(itm) {
                    return $(itm).find('input[type=checkbox]').val();
                });
                _this.selectRowId = selected[0];
            },
        });
    },
    openNewWindow : function (e) {
        var _this = this;
        if (!isEmpty(e)) {
            _this = $(e.target).data('that');
        }
        _this.isEdit = false;
        _this.entity = undefined;
        _this.openWindow('身份识别实体入库');
    },
    openEditWindow : function (e) {
        var _this = this;
        if (!isEmpty(e)) {
            _this = $(e.target).data('that');
        }
        _this.isEdit = true;
        var id = _this.selectRowId;
        if (isEmpty(id)) {
            notification({title : '提示', message : '请选中需要编辑的数据'}, 'info');
            return;
        }
        JsonpAjax(baseApiPath + 'identity/entity/' + id, undefined, 'json', function (res) {
            _this.entity = res;
            _this.openWindow('编辑实体库存信息');
        }, true);

    },
    openWindow : function (title) {
        var _this = this;
        _this.editDiv = _this.sysUtils.openWindow(_this.editDiv, {
            title : title,
            height : "630px",
            width : "650px",
            resizable : false,
            content : 'views/parkLotCenter/parkingLotInfo/identity_edit.html',
            close:function(e){
                //关闭页面上的websocket连接
                clearInterval(identityEntityEdit.timerRead);
                websocketFunManager.removeWebSocket(_this.$parent.parents("li").attr("data-code"));
                this.destroy();
            }
        }, true);
    }
};

var devInfos = new Array();
var IdentityEntityEdit = function ($parent) {
    this.$parent = $parent;
    this.sysUtils = new kendoUtils();
    this.ws = new webSocket(this.handlerMessage, this.openSuccess, this.onClose, identityEntityManager.$parent);
    this.init();
    return this;
}
IdentityEntityEdit.prototype = {
    init : function () {
        var _this = this;
        var fieldArray = this.sysUtils.getBindFieldArray(this.$parent);
        var functionArray = [
            {fName : 'check_device', fs : this.checkDevice},
            {fName : 'save_info', fs : this.saveInfo},
            {fName : 'cancel', fs : function () { $('#' + identityEntityManager.editDiv).data('kendoWindow').close(); identityEntityManager.isEdit = false; identityEntityManager.findData(); }}
        ];
        this.models = new bindBaseModel(null, fieldArray, functionArray, null);
        this.sysUtils.bindDoucment(this.models, this.$parent, this);
        Utils.createDataDictDropDownList({div : _this.$parent.find('#status'), parentModelKey : BASIS.DATA_STATUS.ROOT, select : Utils.getModelValueByModelKey(BASIS.DATA_STATUS.DATA_STATUS_START)}, _this);
        Utils.createDataDictDropDownList({div : _this.$parent.find('#identityType'), parentModelKey : BASIS.IDENTITY_ENTITY_TYPE.ROOT, select : Utils.getModelValueByModelKey(BASIS.IDENTITY_ENTITY_TYPE.IC)}, _this);
        /*  获取外接设备信息 */
        JsonpAjax(baseApiPath + "externalDevice/device_info/ic", undefined, 'json', function(res) {
            var list = res;
            if (devInfos.length > 0) {
                devInfos = new Array();
            }
            for (var i = 0; i < list.length; i++) {
                devInfos.push(list[i]);
            }
            var devices = _this.$parent.find('#device').kendoDropDownList({
                dataTextField : "deviceName",
                dataValueField : "deviceCode",
                dataSource : devInfos,
                change:function(e){
                    _this.checkDeviceStatus = 0;
                }
            }).data('kendoDropDownList');
            devices.select(0);
        }, true);
        this.loadInfo();
    },
    loadInfo : function () {
        if (identityEntityManager.isEdit == true) {
            this.$parent.find('#device_frame').hide();
            this.$parent.find('#console_frame').hide();
            this.$parent.find('mark').show();
            this.$parent.find('.finish-step').show();
            this.sysUtils.setBindFieldValue(identityEntityManager.entity);
            identityEntityManager.entity = undefined;
        }
    },
    openSuccess : function(e) {
        console.log('与后台建立通信正常！');
    },
    onClose : function(e) {
        notification({title : "读卡设备异常", message : "连接断开，请检查设备、网络是否正常，再重新尝试读卡"}, 'info');
        clearInterval(identityEntityEdit.timerRead);
    },
    handlerMessage : function(e) {
        var data = JSON.parse(e.data);
        var $status = $('#readCardStatus');
        if (data.msgType == "REPLY" && data.replyType == "success") {
            if (!isEmpty(identityEntityEdit.readCardSerializeNumber) && identityEntityEdit.readCardSerializeNumber==data.serialNumber) {
                var result = JSON.parse(data.replayMsg);
                var phyid = result.phyid;//物理卡号
                var phytyp = result.phytyp; //物理卡类型
                var cardsno = result.cardsno;//逻辑卡号
                // 读卡成功时
                if (result.opstatus == 1) {
                    if (!isEmpty(identityEntityEdit.phyid) && identityEntityEdit.phyid != phyid) {
                        if (identityEntityEdit.noticeMessage == '当前卡与读卡信息不同，请换会读卡时的磁卡再操作') {
                            return;
                        }
                        identityEntityEdit.noticeMessage = '当前卡与读卡信息不同，请换会读卡时的磁卡再操作';
                        notification({title : '操作失败', message : '当前卡与读卡信息不同，请换会读卡时的磁卡再操作'}, 'info');
                        return;
                    }
                    if (cardsno != '0') {
                        if (identityEntityEdit.noticeMessage == '此卡已发行，请注销后再操作') {
                            $status.css({"color":"red"});
                            $('#readCardStatus').html('此卡已发行，请注销后再操作');
                            return;
                        }
                        identityEntityEdit.noticeMessage = '此卡已发行，请注销后再操作';
                        $status.css({"color":"red"});
                        $('#readCardStatus').html('此卡已发行，请注销后再操作');
                        notification({title : '操作失败', message : '此卡已发行，请注销后再操作'}, 'info');
                        return;
                    }
                    identityEntityEdit.phyid = phyid;
                    identityEntityEdit.phytyp = phytyp;
                    $status.css({"color":"green"});
                    $status.html('读取到卡 {'+phyid+'}');
                    identityEntityEdit.readCardStatus = 1;
                    identityEntityEdit.$parent.find('#identityId').val(phyid);
                    identityEntityEdit.$parent.find('#identityRemark').val(JSON.stringify(result));
                    identityEntityEdit.saveInfo();
                } else {
                    identityEntityEdit.phyid = undefined;
                    $status.css({"color":"red"});
                    $('#readCardStatus').html('读取卡失败');
                }
            } else if (!isEmpty(identityEntityEdit.checkDeviceSerializeNumber) && identityEntityEdit.checkDeviceSerializeNumber == data.serialNumber) {
                // 检测设备成功时
                identityEntityEdit.checkDeviceStatus = 1;
                identityEntityEdit.checkDeviceSerializeNumber = undefined;
                var $device = identityEntityEdit.$parent.find('#device').data('kendoDropDownList');
                var result = $device.dataItem();
                identityEntityEdit.devInfo = result;
                identityEntityEdit.$parent.find('#readCardStatus').html(result.deviceName + ' (' + result.deviceCode + ')');
                identityEntityEdit.$parent.find('#readCardStatus').css({'color':'green'});
                identityEntityEdit.timerRead = setInterval(function() {
                    identityEntityEdit.readCard();
                }, 1000);
            }
        } else {
            notification({title : '提示', message : '设备连接，请检测设备是否连接或重启设备后再试'}, 'info');
            clearInterval(identityEntityEdit.timerRead);
            return;
        }
    },
    readCard : function (e) {
        var _this = this;
        if (!isEmpty(e)) {
            _this = $(e.target).data('that');
        }
        if (_this.checkDeviceStatus != 1) {
            notification({title : '操作失败', message : '请在读卡前测试设备是否连接成功'}, 'info')
            return;
        }
        _this.readCardStatus = 0;
        var $device = _this.$parent.find('#device').data('kendoDropDownList');
        var result = $device.dataItem($device.select());
        var jna = {};
        jna["reader"] = 0; //毒头？
        jna["sector"] = 15; //扇区号
        jna["deviceCacheInfo"] = result;
        var jnaStr = JSON.stringify(jna);
        identityEntityEdit.readCardSerializeNumber = _this.ws.sendMsgToWebSocket(jnaStr,"RC").serialNumber;
    },
    checkDevice : function(e) {
        var _this = this;
        if (!isEmpty(e)) {
            _this = $(e.target).data('that');
        }
        clearInterval(_this.timerRead);
        _this.checkDeviceStatus = 0;
        var $device = _this.$parent.find('#device').data('kendoDropDownList');
        var result = $device.dataItem($device.select());
        if (isEmpty(result) || isEmpty(result.deviceCode)) {
            _this.$parent.find('#deviceStatus').html('请先选择一个读卡器');
            _this.$parent.find('#deviceStatus').css({'color':'red'});
            return;
        }
        var jna = {"volume":1, "voicetext" : result.deviceName + "设备已连接", "lock":0, "deviceCacheInfo":result};
        _this.devInfo = undefined;
        var jnaStr = JSON.stringify(jna);
        _this.checkDeviceSerializeNumber = _this.ws.sendMsgToWebSocket(jnaStr,"VC").serialNumber;
        clearInterval(identityEntityEdit.timerRead);
    },
    saveInfo : function (e) {
        var _this = this;
        if (!isEmpty(e)) {
            _this = $(e.target).data('that');
        }
        clearInterval(_this.timerRead);
        if (validityForm(this.$parent)) {
            var entityParam = _this.sysUtils.getBindDocJson(_this.models.bindFieldArray);
            entityParam['identityId'] = _this.$parent.find('#identityId').val();
            if (entityParam['identityId'] == _this.successPhyid) {
                return;
            }
            entityParam['identityRemark'] = _this.$parent.find('#identityRemark').val();
            var dataT = { 'entityParam' : entityParam };
            JsonpAjax(baseApiPath + 'identity/entity/save', JSON.stringify(dataT), 'json', function (res) {
                if (true == identityEntityManager.isEdit) {
                    identityEntityManager.isEdit = false;
                    identityEntityManager.entity = undefined;
                    identityEntityManager.findData();
                    $('#' + identityEntityManager.editDiv).data('kendoWindow').close();
                    return;
                }
                _this.console(res.results);
                _this.timerRead = setInterval(function() {
                    _this.readCard();
                }, 1000);
            }, true);
        }
    },
    console : function (msg) {
        var _this = this;
        if (_this.cacheMsg == msg) {
            return;
        }
        _this.cacheMsg = msg;
        var date = new Date();
        var $console = _this.$parent.find('#console');
        var str = '['+date.pattern('yyyy/M/d HH:mm:ss')+'] ';
        str += msg;
        str += '<br>';
        $console.prepend(str);
    }
};